package uk.ac.cam.djjb2.mygame;

import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Future;
import java.util.concurrent.RunnableFuture;

public class AsyncPathFinder {
	private final Thread workerThread;
	private ConcurrentLinkedQueue<RunnableFuture<Path>> tasks = new ConcurrentLinkedQueue<RunnableFuture<Path>>();
	
	private static Thread createWorker(final WeakReference<AsyncPathFinder> owner) {
		return new Thread(new Runnable() {
			
			@Override
			public void run() {
				RunnableFuture<Path> task;
				AsyncPathFinder pathFinder;
				
				while ((pathFinder = owner.get()) != null) {
					task = pathFinder.tasks.poll();
					pathFinder = null;
					
					if (task != null) {
						task.run();
					}
					
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	
	public AsyncPathFinder() {
		workerThread = createWorker(new WeakReference<AsyncPathFinder>(this));
		workerThread.start();
	}
	
	public Future<Path> findPath(final PathFinder finder, Vector2i from, Vector2i to) {
		RunnableFuture<Path> task = finder.findPath(from, to);
		
		tasks.add(task);
		
		return task;
	}
}
